<route>
{
meta: {
title: "登录",
constant: true,
layout: false
}
}
</route>

<script setup name="Login">
import api from '@/api'
import { getcaptcha, resetPassword } from '@/api/login/login'
import { useSettingsStore } from '@/store/modules/settings'
import { useUserStore } from '@/store/modules/user'
import bbbb from '@/components/TakeWerk/index.vue'

const diaload = ref(false)
//将子组件引入
// const message = inject('$message')
// const config = inject('$CONFIG')
// const tool = inject('$TOOL')
// // const api = inject('$API')

// const os = ref(false) //控制摄像头开关
// let thisVideo = ref('')
// let thisContext = ref('')
// let thisCancas = ref('')
// const videoWidth = ref(460)
// const videoHeight = ref(350)
// const postOptions = ref([])
// const certCtl = ref('')
// const mask = ref(true)

// //查询参数
// const queryParams = reactive({
//   pageNum: 1,
//   pageSize: 10,
//   imgSrc: undefined,
// })
// const closedPhono = ref(null)

// const emit = defineEmits(['closed'])
// const props = defineProps({
//   visible: { type: Boolean },
// })
// const { visible } = toRefs(props)
// const handleChange = (val) => {
//   console.log(visible)
// }

// //调用摄像头权限
// const getCompetence = () => {
//   nextTick(() => {
//     os.value = false
//     thisCancas = document.getElementById('canvasCamera')
//     thisContext = thisCancas.getContext('2d')
//     thisVideo = document.getElementById('videoCamera')
//     closedPhono.value = thisVideo
//     if (navigator.mediaDevices === undefined) {
//       navigator.mediaDevices = {}
//     }

//     if (navigator.mediaDevices.getUserMedia === undefined) {
//       navigator.mediaDevices.getUserMedia = function (constraints) {
//         // 首先获取现存的getUserMedia(如果存在)
//         let getUserMedia =
//           navigator.webkitGetUserMedia ||
//           navigator.mozGetUserMedia ||
//           navigator.getUserMedia
//         if (!getUserMedia) {
//           return Promise.reject(
//             new Error('getUserMedia is not implemented in this browser')
//           )
//         }
//         return new Promise(function (resolve, reject) {
//           getUserMedia.call(navigator, constraints, resolve, reject)
//         })
//       }
//     }

//     const constraints = {
//       audio: false,
//       video: {
//         width: videoWidth.value,
//         height: videoHeight.value,
//         transform: 'scaleX(-1)',
//       },
//     }

//     navigator.mediaDevices
//       .getUserMedia(constraints)
//       .then(function (stream) {
//         if ('srcObject' in thisVideo) {
//           thisVideo.srcObject = stream
//         } else {
//           thisVideo.src = window.URL.createObjectURL(stream)
//         }
//         thisVideo.onloadedmetadata = function (e) {
//           thisVideo.play()
//         }
//       })
//       .catch((err) => {
//         ElMessage.error('没有开启摄像头权限或浏览器版本不兼容')
//       })
//   })
// }

// //绘制图片
// const drawImage = () => {
//   getCompetence()
//   thisCancas = document.getElementById('canvasCamera')
//   thisContext = thisCancas.getContext('2d')
//   thisVideo = document.getElementById('videoCamera')
//   //thisContext.drawImage(thisVideo, 0, 0, 200, 200)
//   //获取图片地址
//   queryParams.imgSrc = thisCancas.toDataURL('image/png')
//   console.log('图片地址' + queryParams.imgSrc)
// //   const formData = new FormData()
// //   formData.append('file', base64ToFile(queryParams.imgSrc, 'png'))
// //   formData.append('flag', 'videoImg') // 额外参数
//   api
//     .post('face-login', {"imagebast64":queryParams.imgSrc})
//     .then((res) => {
//     })
// }

// //关闭摄像头
// const stopNavigator = () => {
//   // thisVideo = document.getElementById("videoCamera");
//   if (closedPhono.value && closedPhono.value !== null) {
//     thisVideo.srcObject.getTracks()[0].stop()
//     os.value = true
//     diaload.value = false
//   } else {
//     ElMessage.error('没有开启摄像头权限或浏览器版本不兼容')
//   }
// }
// defineExpose({
//   stopNavigator,
// })

const { proxy } = getCurrentInstance()
const route = useRoute(),
  router = useRouter()

const settingsStore = useSettingsStore()

const userStore = useUserStore()

const title = import.meta.env.VITE_APP_TITLE

// 表单类型，login 登录，reset 重置密码
const formType = ref('login')

const loginForm = ref({
  account: localStorage.login_account || '',
  password: '',
  remember: !!localStorage.login_account,
})
const loginRules = ref({
  account: [{ required: true, trigger: 'blur', message: '请输入用户名' }],
  password: [
    { required: true, trigger: 'blur', message: '请输入密码' },
    { min: 6, max: 18, trigger: 'blur', message: '密码长度为6到18位' },
  ],
})

const resetForm = ref({
  account: localStorage.login_account || '',
  captcha: '',
  newPassword: '',
  phone_number: '',
})
const resetRules = ref({
  phone_number: [{ required: true, trigger: 'blur', message: '请输入手机号' }],
  captcha: [{ required: true, trigger: 'blur', message: '请输入验证码' }],
  newPassword: [
    { required: true, trigger: 'blur', message: '请输入新密码' },
    { min: 6, max: 18, trigger: 'blur', message: '密码长度为6到18位' },
  ],
})

const loading = ref(false)
const passwordType = ref('password')
const redirect = ref(null)

onMounted(() => {
  redirect.value = route.query.redirect ?? '/'
})

function showPassword() {
  passwordType.value = passwordType.value === 'password' ? '' : 'password'
  nextTick(() => {
    proxy.$refs.password.focus()
  })
}

function handleLogin() {
  // 登录请求转发
  proxy.$refs.loginFormRef.validate((valid) => {
    if (valid) {
      loading.value = true
      userStore
        .login(loginForm.value)
        .then(() => {
          loading.value = false
          if (loginForm.value.remember) {
            localStorage.setItem('login_account', loginForm.value.account)
          } else {
            localStorage.removeItem('login_account')
          }
          router.push(redirect.value)
        })
        .catch(() => {
          loading.value = false
        })
    }
  })
}

function handleFind() {
  proxy.$message({
    message: '正在重置',
    type: 'info',
  })

  resetPassword(
    resetForm.value.phone_number,
    resetForm.value.captcha,
    resetForm.value.newPassword
  ).then((res) => {
      //判断传递过来的数值

  })
}

function toWerk() {
  diaload.value = true
  getCompetence()
}
const takePhoto = () => {
  //   console.log('visible--->' + clearCamera.value.visible)
  //   visible.value = true
  //console.log('visible--->' + clearCamera.value.visible)
  diaload.value = true
}

const clearIntervals = () => {
  nextTick(() => {
    clearCamera.value.stopNavigator()
  })
  diaload.value = false
  //visible.value = false
}

//验证码改密---获取验证码
const handleTimeChange = () => {
  if (time.value <= 0) {
    isDisposed.value = false
    time.value = 60
  } else {
    setTimeout(() => {
      time.value--
      handleTimeChange()
    }, 1000)
  }
}

const time = ref(60)
const isDisposed = ref(false)

const showcaptcha = () => {
  console.log('手机号' + resetForm.value.phone_number)
  console.log('验证码' + resetForm.value.captcha)
  if (resetForm.value.phone_number == '') {
    alert('请输入正确的手机号')
    return
  }
  getcaptcha(resetForm.value.phone_number).then((res) => {
    isDisposed.value = true
    handleTimeChange()
  })

  //   api.post('user/getcaptcha/' + resetForm.value.phone_number).then((res) => {
  //     isDisposed.value = true
  //     handleTimeChange()
  //   })
}
</script>

<template>
  <div>
    <div class="bg-banner" />
    <div id="login-box">
      <div class="login-banner" />
      <el-form v-show="formType == 'login'"
               ref="loginFormRef"
               :model="loginForm"
               :rules="loginRules"
               class="login-form"
               autocomplete="on"
               label-position="left">
        <div class="title-container">
          <h3 class="title">{{ title }}管理后台</h3>
        </div>
        <div>
          <el-form-item prop="account">
            <el-input ref="name"
                      v-model="loginForm.account"
                      placeholder="用户名"
                      type="text"
                      tabindex="1"
                      autocomplete="on">
              <template #prefix>
                <svg-icon name="user" />
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input ref="password"
                      v-model="loginForm.password"
                      :type="passwordType"
                      placeholder="密码"
                      tabindex="2"
                      autocomplete="on"
                      @keyup.enter="handleLogin">
              <template #prefix>
                <svg-icon name="password" />
              </template>
              <template #suffix>
                <svg-icon :name="passwordType === 'password' ? 'eye' : 'eye-open'"
                          @click="showPassword" />
              </template>
            </el-input>
          </el-form-item>
        </div>
        <div class="flex-bar">
          <el-checkbox v-model="loginForm.remember">记住我</el-checkbox>
          <el-button type="text"
                     @click="formType = 'reset'">
            忘记密码
          </el-button>
          <el-button type="primary"
                     @click="takePhoto">人脸识别登录</el-button>
        </div>
        <el-button :loading="loading"
                   type="primary"
                   size="large"
                   style="width: 100%;"
                   @click.prevent="handleLogin">
          登 录
        </el-button>
        <!-- <div style="margin-top: 20px; margin-bottom: -10px; color: #666; font-size: 14px; text-align: center; font-weight: bold;">
                    <span style="margin-right: 5px;">演示帐号一键登录：</span>
                    <el-button type="danger" size="small" @click="testAccount('admin')">admin</el-button>
                    <el-button type="danger" size="small" plain @click="testAccount('test')">test</el-button>
                </div> -->
      </el-form>
      <bbbb ref="clearCamera"
            @pagination='takePhoto'
            v-if="diaload"
            @closed="clearIntervals" />

      <el-form v-show="formType == 'reset'"
               ref="resetFormRef"
               :model="resetForm"
               :rules="resetRules"
               class="login-form"
               auto-complete="on"
               label-position="left">
        <div class="title-container">
          <h3 class="title">重置密码</h3>
        </div>
        <div>
          <el-form-item prop="phone_number">
            <el-input ref="name"
                      v-model="resetForm.phone_number"
                      placeholder="手机号"
                      type="text"
                      tabindex="1"
                      autocomplete="on">
              <template #prefix>
                <svg-icon name="user" />
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="captcha">
            <el-input ref="captcha"
                      v-model="resetForm.captcha"
                      placeholder="验证码"
                      type="text"
                      tabindex="2"
                      autocomplete="on">
              <template #prefix>
                <svg-icon name="captcha" />
              </template>
              <template #append>
                <el-button @click="showcaptcha"
                           :disabled="isDisposed">{{ isDisposed ? `${time}s后重新获取` : "获取验证码" }}</el-button>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="newPassword">
            <el-input ref="newPassword"
                      v-model="resetForm.newPassword"
                      :type="passwordType"
                      placeholder="新密码"
                      tabindex="3"
                      autocomplete="on">
              <template #prefix>
                <svg-icon name="password" />
              </template>
              <template #suffix>
                <svg-icon :name="passwordType === 'password' ? 'eye' : 'eye-open'"
                          @click="showPassword" />
              </template>
            </el-input>
          </el-form-item>
        </div>
        <el-row :gutter="15"
                style="padding-top: 20px;">
          <el-col :md="6">
            <el-button size="large"
                       style="width: 100%;"
                       @click="formType = 'login'">
              去登录
            </el-button>
          </el-col>
          <el-col :md="18">
            <el-button :loading="loading"
                       type="primary"
                       size="large"
                       style="width: 100%;"
                       @click.prevent="handleFind">
              确 认
            </el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <Copyright v-if="settingsStore.copyright.enable" />
  </div>

</template>

<style lang="scss" scoped>
[data-mode='mobile'] {
  #login-box {
    max-width: 80%;

    .login-banner {
      display: none;
    }
  }
}

:deep(input[type='password']::-ms-reveal) {
  display: none;
}

.bg-banner {
  position: absolute;
  z-index: 0;
  width: 100%;
  height: 100%;
  background-image: url('../assets/images/login-bg.jpg');
  background-size: cover;
  background-position: center center;
}

#login-box {
  display: flex;
  justify-content: space-between;
  position: absolute;
  top: 60%;
  left: 75%;
  transform: translateX(-50%) translateY(-50%);
  background: rgb(255 255 255 / 80%);
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 0 5px #999;

  .login-banner {
    width: 0px;
    background-image: url('../assets/images/login-banner.jpg');
    background-size: cover;
    background-position: center center;
  }

  .login-form {
    width: 400px;
    padding: 50px 35px 30px;
    overflow: hidden;

    .title-container {
      position: relative;

      .title {
        font-size: 22px;
        color: #666;
        margin: 0 auto 30px;
        text-align: center;
        font-weight: bold;
        @include text-overflow;
      }
    }
  }

  :deep(.el-input) {
    height: 48px;
    line-height: inherit;
    width: 100%;

    input {
      height: 48px;
    }

    .el-input__prefix,
    .el-input__suffix {
      display: flex;
      align-items: center;
    }

    .el-input__prefix {
      left: 10px;
    }

    .el-input__suffix {
      right: 10px;
    }
  }

  .flex-bar {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .el-checkbox {
    margin: 20px 0;
  }
}

.copyright {
  position: absolute;
  bottom: 30px;
  width: 100%;
  margin: 0;
  mix-blend-mode: difference;
}
.footer {
  width: 200px;
  height: 50px;
  background-color: white;
  justify-content: space-between;
  float: left;
  margin-top: 100px;
  margin-left: 100px;
}
.detailed {
  width: 1200px !important;
  height: 800px !important;
  display: block;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  background-color: white;
}

.oText {
  margin-left: 42px;
}
.mask {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 999;
}
.closeBtn {
  float: right;
}
.box {
  width: 460px;
  height: 300px;
  margin-top: 10px;
  background-color: rgba(0, 0, 0, 0.5);
  float: left !important;
}
.go {
  width: 500px;
  height: 500px;
  background-color: white;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  display: inline-block;
}
</style>
